<template>
  <div class='box-wrap-ws'>
    <div class="box-top">
      <div>
        <span>业务方案配置说明</span>
        <span>
         1.平台若更改业务价格，客户使用的业务方案均会更改为系统默认方案；<br>
         2.业务价格不能低于平台业务价格，业务价格不能高于平台业务价格*2；<br>
         3.业务价格仅更改需要修改业务价格即可，其它业务价格不修改会自动默认为平台价格；<br>
        </span>
      </div>

    </div>
    <section class='box-operation'>
      <div class="box-search">
        <!-- <div class='form-group-enquire'><Input v-model.trim="searchData.name" placeholder="业务类型" clearable @on-enter="onSearchGetList()"></Input></div>
        <div class='form-group-enquire'>
          <el-select v-model="searchData.sieve_source_config_id" placeholder="请选择筛料源" clearable filterable>
            <el-option :value= row.id v-for="row in statuslist" :label="row.name" :key= row.id >{{row.name}}</el-option>
          </el-select>
        </div> -->

        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg6' @click='editInfo({},5)'><img src="../../assets/images/peach-svg/add.svg"></div>
        <!-- <div class='form-group-addimg6' @click='editInfo({},1)'><img src="../../assets/images/peach-svg/mach.svg"></div> -->
        <div class='form-group-addimg2' @click='downloadFile(1,{})'><img src="../../assets/images/peach-svg/export.svg"></div>
      </div>
    </section>
    <LibVxeTable class="fbstaticData" :stripe="stripe"  border="none"
    :tableColumns="tableColumns" :tableData="list"
    :slotHeader="slotHeader"
    :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"
    @onPageChange="onChangePageSize"
    @onSelectChange="onCheckChange"
    resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import {ACDN} from '../../commons/staticName'
import bus from "../../commons/EventBus"

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    const validateName = (rule, value, callback) =>{
      if(value == "" || value == undefined){
        callback(new Error("名称不能为空"));
      }else if(value.length > 20 ){
        callback(new Error("名称长度不能超过20"));
      }else {
        callback();
      }
    };
    const validateunit_p = (rule, value, callback) =>{
      if(value == "" || value == undefined){
        callback(new Error("单价不能为空"));
      }else if(value <=0 ){
        callback(new Error("单价不能小于0"));
      }else if(value < 0.0001 || value > 0.01){
        callback(new Error("单价不合理，请重新设置单价（单价范围：0.0001元 - 0.01元）"));
      }else {
        callback();
      }
    };
    const validateNew_id = (rule, value, callback) =>{
      if(value == "" || value == undefined){
        callback(new Error("请先选择业务方案！"));
      }else {
        callback();
      }
    };
    return {
      statuslist: [],
      stripe:false,
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        creator_name:"",
        name:"",
        page_index:1,
        page_size:30,
        with_def:1,
        sieve_source_config_id:''
      },
      sieve_source_config_id:"",
      mnoList:{},
      pricesList:[],
      provinceList:{},
      list:[],
      totalCnt:0,
      info:{},
      formPopIndex:0,
      roles:[],
      leaders:[],
      roleObj:{},
      CountryList:[],
      leaderlist:[],
      footerMethod:{},
      Types:[],
      idlistObj:{},
      nameobj:[],
      selectRows :[],
      SailiaoObj:{},
      tableColumns:[
        {
        field: "Id",
        type:"checkbox",
        align: "center",
        width:50,
        },
        {
          title: "业务方案",
          field: "name",
          align: 'center',
        },
        {
          title: "说明",
          field: "description",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.description==''||row.description==undefined) {
                    return [h("span","--")]
                }else{
                    return row.description
                }
            }
          }
        },
         {
          title: "用户数",
          field: "user_count",
          align: "center",
          slots:{
            default:({row},h) =>{
              return this.$AutoFun(()=>{
              let hButton = [];
                   hButton.push(
                  h(
                    "a",
                    {
                      props: { type: "danger", size: "small"},
                      style: { marginRight: "5px" },
                      on: {
                        click: () => {
                          this.userCount(row);
                        }
                      }
                    },row.user_count
                  )
                );
              return hButton;
            });
            }
          }
        },
        
         {
          title: "最后修改时间",
          field: "updated_at",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.updated_at==0){
                return [h("div",'-')]
              }else
              return [h("div",utils.dateFormat(row.updated_at,"yyyy-MM-dd HH:mm:ss"))]
            }
          }
        },
        
        {
          title: "操作",
          field: "action",
          width: 150,
          align: "center",
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];
              hButton.push(h(
                    "div",
                    {
                      class:"looklook",
                      on: {
                        click: () => {
                          this.lookInfo(row);
                        }
                      }
                    },
                  ));
                
                 if(row.def!=1){
                  hButton.push(h(
                    "div",
                    {
                      class:"two",
                      on: {
                        click: () => {
                          this.editInfo(row,2);
                        }
                      }
                    },
                  ));
                   hButton.push(
                  h(
                    "div",
                    {
                      props: { type: "danger", size: "small" },
                      style: { marginRight: "5px" },
                      class:"three",
                      on: {
                        click: () => {
                          this.editInfo(row,-1);
                        }
                      }
                    },
                  )
                );
                 }
              return hButton;
            });
            }
          }
        }
      ],
      format: {
        name:{
          labelName: "方案名称",
          labelType: "text",
          placeholder:"请输入方案名称",
        },
        description:{
          labelName: "说明",
          labelType: "textarea",
          placeholder:"请输入说明",
          maxlength:50
        },
        sieve_source_config_id:{
          labelName: "价格配置",
          labelType: "select",
          placeholder:"价格配置",
          labelValue:[],
          labelChange:"sieve_source_config_id"
        },
        prises:{
          label:"",
          labelType:"tableprice",
          labelValue:[]
        },
        new_id:{
          label:"",
          labelType:"select",
          labelName: "业务方案",
          labelValue:[],
        },
      },
      ruleValidate: {
        name: [{ required: true,validator:validateName, trigger: "blur" }],
        unit_price:[{ required: true,validator:validateunit_p, trigger: "blur" }],
        new_id:[{ required: true,validator:validateNew_id, trigger: "blur" }],
      },
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        await this.getList();
        await this.queryTypes();
        // await this.initPrice()
      }
      let res3 = await Request.post("customer/businessPrice","query_list",{def:1})//默认业务方案id
      this.priceId = res3.data.list[0].id || ""
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData);
      this.pricesList=[]
        const defone=this.priceId
        let res32 = await this.RequestPost("queryDetail_item",{id:defone,def:1});
        if(res32.data!=null){
          res32.data.forEach(res =>{
            this.pricesList.push({name:res.name,desc:res.desc,unit_price:res.unit_price/10000})
          })
        }
        this.format.prises.labelValue=this.pricesList
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null)
        this.list = res.data.list;
        this.totalCnt = res.data.total
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },
    //多选框数组
    onCheckChange(rows){  
        this.selectRows = [];
        this.selectRows = rows;
    },
    async queryTypes(){
    },
    async initPrice(){
      let res2 = await Request.post("customer/businessPrice","query_list",{with_def:1})//业务方案接口
      
      let pricesList = res2.data.list || []
      this.pList = pricesList.map(item=>{
        return{
          id:item.id,
          name:item.name,
          desc:item.description
        }
      })
      let res4 = await Request.post("customer/businessPrice","queryDetail_item",{id:this.priceId})//筛料源接口
      let pricesList2 = res4.data || []
      this.pList2 = pricesList2.map(item=>{
        return{
          id:item.id,
          name:item.name,
          desc:item.desc, 
          unit_price:item.unit_price/10000
        }
      })
    },
    //查看
    async lookInfo(row){
      //  await this.initPrice()
       let priceList = row.prices || []
        priceList = priceList.map(item => {
          const priceItem = this.pricesList.find(item2 => item2.name === item.name) || {}
          return {
            name: item.name,
            desc: priceItem.desc,
            unit_price: priceItem.unit_price,
            price: item.unit_price / 10000
          }
        })
        let info = {};
        info = {
          id:row.id,
          name:row.name,
          description:row.description,
          unit_price:row.unit_price/10000,
          prises: priceList
        };
        let title = "查看配置"
        this.format.prises.labelValue=priceList
        this.format.prises.labelDisabled= true
        this.handleType = 8
        this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
      );
    },
    //添加 编辑用户
    async editInfo(row,type) {
      let title = "";
      let info = {};
      this.handleType = type
      await this.initPrice()
      if(type==1){  
        title = "批量修改筛料源";
        let new_ids=""
        if((this.selectRows.checked==true && this.selectRows.records.length>= 1)||(this.selectRows.checked==false && this.selectRows.records.length>= 1)){
          //导出值用id|id形式拼接
          this.selectRows.records.forEach(item => {
            new_ids+='|'+item.id
          });
          if(new_ids!=''){
            new_ids=new_ids.substring(1)
          }
         }
         info = {
            ids:new_ids,
            sieve_source_config_id:""
          };
      }else if(type==2){
        let priceList = row.prices || []
        priceList = priceList.map(item => {
          const priceItem = this.pricesList.find(item2 => item2.name === item.name) || {}
          return {
            name: item.name,
            desc: priceItem.desc,
            unit_price: priceItem.unit_price,
            price: item.unit_price / 10000
          }
        })
        title = "修改配置"
        this.format.prises.labelValue=priceList
        this.format.prises.labelDisabled= false
        info = {
          id:row.id,
          name:row.name,
          description:row.description,
          unit_price:row.unit_price/10000,
          prises: priceList
        };
      }else if(type==5){
        title = "新增配置"
        info = {
          name:"",
          description:"",
          unit_price:"",
          sieve_source_config_id:this.priceId,
          prises:""
        };
        this.onSelectChange("sieve_source_config_id",info.sieve_source_config_id);
        this.format.prises.labelValue=this.pricesList
        this.format.prises.labelDisabled= false
        this.format.sieve_source_config_id.labelValue = this.pList
      }else if(type==-1){
        title = "删除"+"《"+row.name+"》"
        let deleteList=this.list.filter(item=>{
           return item.id!==row.id
        })
        this.format.new_id.labelValue=deleteList
        info = {
          id:row.id,
          new_id:""
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,message:type==-1?"请指定业务方案给该方案所使用用户，请谨慎操作！":"",el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==1) {
          actionName = 'updateBatch_item';
          tipText = '筛源修改成功！';
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '修改成功！';
        const arr2 = info["prises"] || []
        const mapArr2 = arr2.map(item => {
          return {
            name: item.name,
            unit_price: Math.round(item.price*10000) || Math.round(item.unit_price*10000)
          }
        })
        postData["prices"] = JSON.stringify(mapArr2)
        delete postData["prises"]
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        delete postData["prises"]
      }else if(this.handleType==3){
        actionName = 'enable_item';
        tipText = '启用成功！';
        postData = {"id":postData.id};
      }else if(this.handleType==4){
        actionName = 'disable_item';
        tipText = '禁用成功！！';
        postData = {"id":postData.id};
      }else if(this.handleType==5){
        actionName = 'add_item';
        tipText = '添加成功！！';
        const arr = info["prises"] || []
        const mapArr = arr.map(item => {
          return {
            name: item.name,
            unit_price: Math.round(item.price*10000) || Math.round(item.unit_price*10000)
          }
        })
        postData["prices"] = JSON.stringify(mapArr)
        delete postData["prises"]
      }
      else if(this.handleType===8){
        utils.hideFormPage(this.formPopIndex)
        utils.hideLoading();
        return
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
        console.log(postData,"postDatapostData")
      }else{
        utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
          "modalContent":res.data,
          "title":"提示"});
      }
      utils.hideLoading();
    },

    //用户数跳转
    async userCount(row){
      let res2 = await Request.post("customer/user","query_list",{business_price_id:row.id})//业务方案接口
      let userl = res2.data || []
      bus.$emit('searchuser','')
      bus.$on("userHasRender",()=>{
         bus.$emit("user-count-list",userl)
         bus.$emit("user-count-Id",row.id)
      })
      bus.$emit("user-count-list",userl)
      bus.$emit("user-count-Id",row.id)
    },
     //导出列表
    async downloadFile() {
      // utils.showLoading("正在生成中")
      let new_ids=""
      if((this.selectRows.checked==true && this.selectRows.records.length!= 0)||(this.selectRows.checked==false && this.selectRows.records.length!= 0)){
        //导出值用id|id形式拼接
        this.selectRows.records.forEach(item => {
          new_ids+='|'+item.id
        });
        if(new_ids!=''){
          new_ids=new_ids.substring(1)
        }
        let res = await this.RequestPost("export_list",{"ids":new_ids});
        if(res.code==0){
          utils.hideLoading()
            await utils.sleepMs(500);
            // utils.showTip("导出成功，在IM中查收");
        }
        window.location.href = ACDN+res.data
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请至少选择一项 ",
         "title":"提示"});
      }

    },
    async onSelectChange(label,value,reset){
       if(label=="sieve_source_config_id"){
          let res = await Request.post("customer/businessPrice","query_list",{with_def:1,id:value});
          let nowScheme = value === this.priceId ? res.data.list[0] || [] : res.data.list[1] || []
          let priceList = nowScheme.prices || []
          priceList = priceList.map(item => {
            const priceItem = this.pricesList.find(item2 => item2.name === item.name) || {}
            let price = value === this.priceId ? true : false
            if(price){
              return {
                name: item.name,
                desc: priceItem.desc,
                unit_price: priceItem.unit_price,
              }
            }else{
              return {
                name: item.name,
                desc: priceItem.desc,
                unit_price: priceItem.unit_price,
                price: item.unit_price / 10000
              }
            }
          })
          this.format.prises.labelValue=priceList
        }
    },
    onChangePageSize(page,pageSize){
      this.modal = true
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(val){
      let num = new Date(val)
      let time = num.getTime()/1000;
      // this.searchData.create_at = time
    },
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    unitprice(data){
      let unit_price = 0
      data.forEach(item =>{
        unit_price+=item.unit_price
      })
      return unit_price
    },
    showFooter(){
     if(this.footerMethod){
         return true;
     }else{
         return false;
     }
    }
  },
};
</script>
